import { io } from 'socket.io-client'
// const ioc = require("socket.io-client");

// export default class Net {
//     constructor(type,remoteAddr, data){
//         this.remoteAddr = remoteAddr
//         this.server = window.location.host
//         // generate a random 8-id for the client by time
//         this.id = Date.now().toString(36)
//         this.socket = null;
//         this.type = type;
//         this.data = data;
//         this.options = {}
//     }

//     connect(callback, end_callback){
//         let self = this;
//         this.socket = io(this.server,{transports: ['websocket']});
//         this.socket.on('connect', function() {
            
//             // 发送数据到后端
//             console.log('send message to server:',self.id, self.remoteAddr, self.data, self.type, self.options);
//             self.socket.emit('message', { 
//                 id: self.id,
//                 remote: self.remoteAddr,
//                 data: self.data,
//                 type: self.type,
//                 headers: self.options.headers,
//                 stream: self.options.use_stream,
//                 usepost: self.options.usepost,
//                 cookie: self.options.cookie,
//             });
//         });

//         // 监听来自后端的stream_data事件
//         this.socket.on(self.id, function(data) {
//             // console.log('Received stream data:', data);
//             let j = JSON.parse(data)
//             if (j.end != null){
//                 self.socket.close();
//                 end_callback()
//             }else{
//                 callback(j);
//             }
//             // 处理接收到的数据
            
//         });

//         // 监听断开连接事件
//         this.socket.on('disconnect', function() {
//             console.log('Disconnected from server');
//             end_callback()
//         });


//     }
// }


export default class Net {
    constructor(type, remoteAddr, data) {
        this.remoteAddr = remoteAddr;
        this.server = `ws://${window.location.host}/socket.io`; // WebSocket URL
        this.id = Date.now().toString(36);
        this.socket = null;
        this.type = type;
        this.data = data;
        this.options = {};
    }

    connect(callback, end_callback) {
        let self = this;
        // 创建WebSocket连接
        this.socket = new WebSocket(this.server);

        // 连接成功时触发
        this.socket.onopen = function() {
            console.log('Connected to server');
            // 发送数据到后端
            console.log('send message to server:', self.id, self.remoteAddr, self.data, self.type, self.options);
            const message = {
                id: self.id,
                remote: self.remoteAddr,
                data: self.data,
                type: self.type,
                headers: self.options.headers,
                stream: self.options.use_stream,
                usepost: self.options.usepost,
                cookie: self.options.cookie,
            };
            self.socket.send(JSON.stringify(message));
        };

        // 接收消息时触发
        this.socket.onmessage = function(event) {
            const data = event.data;
            try {
                const j = JSON.parse(data);
                console.log("ws:",j.id, "my id:",self.id, j,j.id === self.id,j.end)
                if (j.id === self.id) { // 确保消息是针对当前连接的
                    if (j.end !== null && j.end != undefined) {
                        console.log("ws:","end")
                        self.socket.close();
                        end_callback();
                    } else {
                        console.log("ws:",j)
                        if (j.data != null){
                            callback(JSON.parse(j.data));
                        }else{0
                            console.log("lack data!!!")
                        }
                    }
                }
            } catch (error) {
                console.error('Error parsing message:', error);
            }
        };

        // 连接关闭时触发
        this.socket.onclose = function() {
            console.log('Disconnected from server');
            end_callback();
        };

        // 处理连接错误
        this.socket.onerror = function(error) {
            console.error('WebSocket error:', error);
            end_callback();
        };
    }
}